var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Mp3Schema = new Schema({
    title: String, //名称
    album: String, //所属专辑
    artist: String, //作者
    mp3: String, //路径
    poster: String, //海报地址
    plays: { //播放次数
        type: Number,
        default: 0
    },
    meta: {
        createAt: { //创建时间
            type: Date,
            default: Date.now()
        },
        updataAt: { //更新时间
            type: Date,
            default: Date.now()
        }
    }
});

/**
 * 新增MP3
 */
Mp3Schema.pre('save', function(next) {
    var mp3 = this;
    if (mp3.isNew) {
        mp3.meta.createAt = mp3.meta.updataAt = Date.now();
    } else {
        mp3.meta.updataAt = Date.now();
    }
    next();
});
Mp3Schema.statics = {
    fetch: function(cb) {
        return this
            .find({})
            .sort('meta.updataAt')
            .exec(cb)
    },
    fetchByAttr: function(value, cb) {
        return this
            .find()
            .sort('meta.createAt')
            .exec(cb)
    },
    findOneByAttr: function(value, cb) {
        return this
            .findOne(value)
            .exec(cb)
    },
    top: function(pagesize, pageindex, cb) {
        return this
            .find({})
            .skip(pagesize * (pageindex - 1), cb)
            .limit(pagesize)
            .sort('meta.updateAt')
            .exec(cb)
    }
}
module.exports = Mp3Schema;
